package com.coolrui.domain.dubbo.provider;

import com.coolrui.api.dto.UserOrderDTO;
import com.coolrui.api.dto.UserOrderListDTO;
import com.coolrui.api.service.UserOrderService;
import com.coolrui.common.system.ApiList;
import com.coolrui.domain.dubbo.utils.OrderConvertUtils;
import com.coolrui.domain.order.entity.UserOrder;
import com.coolrui.domain.order.service.UserOrderDomainService;
import com.coolrui.domain.order.service.UserOrderHandleService;
import com.coolrui.domain.prometheus.OrderMetricsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@DubboService
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private UserOrderHandleService userOrderHandleService;
    @Autowired
    private UserOrderDomainService userOrderDomainService;
    @Autowired
    private OrderConvertUtils orderConvertUtils;
    @Autowired
    private OrderMetricsService orderMetricsService;

    @Override
    public UserOrderDTO createOrder(Long userId) {
        //监控埋点-请求QPS指标
        orderMetricsService.recordRequest("createOrder");
        UserOrder order = userOrderHandleService.getMockOrder(userId);
        int ret = userOrderDomainService.createOrder(order);
        if (ret <= 0) {
            log.error("创建用户订单失败, userId: {}", userId);
            return null;
        }
        //监控埋点-订单总金额指标
        orderMetricsService.recordAmount(order.getOrderPrice());

        //转换返回DTO实体
        UserOrderDTO orderDTO = orderConvertUtils.toUserOrderDTO(order);
        log.info("创建用户订单, userId: {}, orderDTO: {}", userId, orderDTO);
        return orderDTO;
    }

    @Override
    public UserOrderDTO queryOrder(Long orderId) {
        //监控埋点-QPS指标
        orderMetricsService.recordRequest("queryOrder");
        UserOrder order = userOrderDomainService.getOrder(orderId);
        if (order == null) {
            log.warn("查询用户订单, orderId: {}, 订单不存在", orderId);
            return null;
        }
        //转换返回DTO实体
        UserOrderDTO orderDTO = orderConvertUtils.toUserOrderDTO(order);
        log.info("查询用户订单, orderId: {}, orderDTO: {}", orderId, orderDTO);
        return orderDTO;
    }

    @Override
    public UserOrderListDTO queryOrderList(Long userId, Integer page, Integer pageSize) {
        //监控埋点-QPS指标
        orderMetricsService.recordRequest("queryOrderList");
        ApiList<UserOrder> orderList = userOrderDomainService.getOrderList(userId, page, pageSize);
        //转换返回DTO列表实体
        List<UserOrderDTO> orderDTOList = orderConvertUtils.toUserOrderDTOList(orderList.getList());
        log.info("查询用户订单列表, userId: {}, page: {}, pageSize: {}, orderDTOList: {}", userId, page, pageSize, orderDTOList);
        return new UserOrderListDTO(orderList.getHasMore(), orderDTOList);
    }
}
